<?php
/**
 * Account_model
 *
 * @uses TXT_Model
 * @package
 * @version $id$
 * @copyright 2003-2011 The PHP Developer
 * @author lingfeng <cnlingfeng@gmail.com>
 * @license PHP Version 5.2 {@link http://www.php.net/}
 */
class Account_model extends TXT_Model {

    /*
     * 状态：正常
     */
    const STATUS_NORMAL = 1;

    /*
     *  状态：删除
     */
    const STATUS_REMOVE = 9;

    /**
     *  日志状态：成功
     */
    const LOG_STATUS_NORMAL = 1;

    /**
     *  日志状态：失败
     */
    const LOG_STATUS_FAIL = 2;

    /**
     *  日志类型：充值
     */
    const LOG_TYPE_CHARGE = 1;

    /**
     *  日志类型：发送
     */
    const LOG_TYPE_SENT = 2;

    /**
     *  日志类型：分配
     */
    const LOG_TYPE_ASSIGN = 3;

    /*
     * _table
     * 账户表名
     *
     * @var string
     * @access private
     */
    private $_table = 'accounts';

    /*
     * _log_table
     * 账户日志表名
     *
     * @var string
     * @access private
     */
    private $_log_table = 'account_logs';

    /*
     * __construct
     * 构造函数
     *
     * @access protected
     * @return void
     */
    function __construct() {
        parent::__construct();
        $this->load->database('default');
    }

    /**
     * addAccount
     * 添加账号
     *
     * @access public
     * @return aid
     */
    function addAccount($uid) {

        if(!$uid) {
            return false;
        }

        $insertData = array(
            'uid' => $uid,
            'a_status' => self::STATUS_NORMAL,
            'a_created' => date($this->config->item('log_date_format'))
        );
        return $this->db->insert($this->_table, $insertData);
    }

    /**
     * incrAccount 
     * 添加账户金额
     * 
     * @param integer $uid 用户ID
     * @param integer $sp 服务商ID
     * @param integer $a_balance_amount 
     * @access public
     * @return void
     */
    function incrAccount($uid, $sp, $a_balance_amount = 0) {

        if(!$uid) {
            return false;
        }

        if(!$a_balance_amount) {
            return fasle;
        }

        $a_updated = date($this->config->item('log_date_format'));
        $this->db->set('a_total_amount', 'a_total_amount + '.$a_balance_amount, false);
        $this->db->set('a_balance_amount', 'a_balance_amount + '.$a_balance_amount, false);
        $this->db->set('a_sp', $this->_incrSpAccount($uid, $sp, $a_balance_amount));
        $this->db->set('a_updated', $a_updated);
        $this->db->where('uid', $uid);
        $this->db->update($this->_table);
        return true;
    }

    /**
     * _incrAccount 
     * 增加某SP的账户
     * 
     * @param mixed $uid 
     * @param mixed $sp 
     * @param mixed $balance_amount 
     * @access private
     * @return void
     */
    private function _incrAccount($uid, $sp, $balance_amount) {

        $accountInfo = $this->getAccountByUid($uid, false);

        if (!$accountInfo) {
            return '';
        }

        $accountInfo = $this->_decodeSp($accountInfo);

        if ($accountInfo['a_sp'][$sp]) {
            $accountInfo['a_sp'][$sp]['total_amount'] += $balance_amount;
            $accountInfo['a_sp'][$sp]['balance_amount'] += $balance_amount;
        } else {
            $accountInfo['a_sp'][$sp] = array(
                'total_amount' => $balance_amount,
                'balance_amount' => $balance_amount,
                'used_amount' => 0,
            );
        }

        $accountInfo = $this->_encodeSp($accountInfo);
        return $accountInfo['a_sp'];
    }

    /**
     * decrAccount 
     * 减少账户金额
     * 
     * @param integer $uid 用户ID
     * @param integer $sp 服务商ID
     * @param integer $amount 金额
     * @access public
     * @return void
     */
    function decrAccount($uid, $sp, $amount = 0) {

        if(!$uid) {
            return false;
        }

        if(!$amount) {
            return false;
        }

        $a_updated = date($this->config->item('log_date_format'));
        $sp = $this->_decrSpAccount($uid, $sp, $amount);

        if ($sp) {
            $this->db->set('a_balance_amount', 'a_balance_amount - ' . $amount, false);
            $this->db->set('a_used_amount', 'a_used_amount + ' . $amount, false);
            $this->db->set('a_sp', $sp);
            $this->db->set('a_updated', $a_updated);
            $this->db->where('uid', $uid);
            $this->db->where('a_balance_amount >= ', $amount);
            return $this->db->update($this->_table);
        } else {
            return false;
        }
    }

    /**
     * _decrAccount 
     * 增加某SP的账户
     * 
     * @param mixed $uid 
     * @param mixed $sp 
     * @param mixed $balance_amount 
     * @access private
     * @return void
     */
    private function _decrAccount($uid, $sp, $amount) {

        $accountInfo = $this->getAccountByUid($uid, false);

        if (!$accountInfo) {
            return '';
        }

        $accountInfo = $this->_decodeSp($accountInfo);

        if ($accountInfo['a_sp'][$sp] && $accountInfo['a_sp'][$sp]['balance_amount'] >= $amount) {
            $accountInfo['a_sp'][$sp]['balance_amount'] -= $amount;
            $accountInfo['a_sp'][$sp]['used_amount'] += $amount;
        } else {
            return '';
        }

        $accountInfo = $this->_encodeSp($accountInfo);
        return $accountInfo['a_sp'];
    }

    /**
     * deleteAccount
     * 删除账号
     *
     * @access public
     * @return aid
     */
    function deleteAccount($uid) {

        if(!$uid) {
            return false;
        }

        $deleteData = array(
            'uid' => $uid,
            'a_status' => self::STATUS_REMOVE,
            'a_deleted' => date($this->config->item('log_date_format'))
        );
        return $this->db->update($this->_table, $updateData, array('uid'=>$uid));
    }

    /**
     * getAccountByUid
     * 根据UID获取账户信息
     *
     * @param integer $uid 用户ID
     * @param boolean $mergeUser 合并用户信息
     * @access public
     * @return array
     */
    function getAccountByUid($uid, $mergeUser = true) {

        if(!$uid) {
            return false;
        }

        $query = $this->db->get_where($this->_table, array('uid' => $uid, 'a_status !=' => self::STATUS_REMOVE));
        $data = $query->row_array();

        // 获取用户数据
        if ($mergeUser) {
            $this->load->model('user_model');
            $userInfo = $this->user_model->getUserByUid($uid);

            if ($userInfo) {
                $data = $data + $userInfo;
            }
        }

        return $data;
    }

    /**
     * _decodeSp
     * 解码SP
     *
     * @param array $accountInfo
     * @access private
     * @return array
     */
    private function _decodeSp($accountInfo) {

        $accountInfo['a_sp'] = json_decode($accountInfo['a_sp']);
        return $accountInfo;
    }

    /**
     * _encodeSp
     * 编码SP
     *
     * @param array $accountInfo
     * @access private
     * @return array
     */
    private function _encodeSp($accountInfo) {

        $accountInfo['a_sp'] = json_encode($accountInfo['a_sp']);
        return $accountInfo;
    }

    /**
     * listAccountLog 
     * 获取商户日志列表
     * 
     * @param integer $aid 账户ID
     * @param array $pageOptions 分页数组
     * @access public
     * @return void
     */
    function listAccountLog($aid, &$pageOptions) {

        // 总记录数
        if (!$pageOptions['total_rows']) {
            $this->db->where('aid', $aid);
            $this->db->where('al_status !=', self::STATUS_REMOVE);
            $this->db->from($this->_log_table);
            $pageOptions['total_rows'] = $this->db->count_all_results();
        }

        $this->_resolvePageOptions($pageOptions);

        $this->db->order_by('alid', 'DESC');
        $query = $this->db->get_where($this->_log_table, array('aid' => $aid, 'al_status !=' => self::STATUS_REMOVE),
            $pageOptions['per_page'], $pageOptions['curr_page']);

        $data = array();

        foreach($query->result_array() as $row) {
            $data[] = $row;
        }

        return $data;
    }

    /**
     * addAccountLog 
     * 添加账户日志记录
     * 
     * @param integer $aid 账户ID
     * @param integer $type 日志类型
     * @param integer $sp 服务商ID
     * @param integer $amount 金额
     * @param integer $balance_amount 余额
     * @param string $event 事件
     * @access public
     * @return boolean
     */
    function addAccountLog($aid, $type, $sp, $amount, $balance_amount, $event) {

        $insertData = array(
            'aid' => $aid,
            'al_type' => $type,
            'a_sp' => $sp,
            'al_amount' => $amount,
            'al_balance_amount' => $balance_amount,
            'al_event' => $event,
            'al_status' => self::LOG_STATUS_NORMAL,
            'al_created' => date($this->config->item('log_date_format'))
        );

        return $this->db->insert($this->_log_table, $insertData);
    }
}
?>
